package cn.aigoubuy.web.servelt;

import cn.aigoubuy.domain.Cart;
import cn.aigoubuy.domain.CartItem;
import cn.aigoubuy.domain.Product;
import cn.aigoubuy.service.ProductService;
import cn.aigoubuy.service.impl.ProductServiceImpl;
import cn.aigoubuy.web.base.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/cartServlet")
public class CartServlet extends BaseServlet {
    /**
     * 添加商品到购物车
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String addToCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1.获得请求参数
        // 商品 id
        String pid = request.getParameter("pid");
        // 获取购买数量
        int count = Integer.parseInt(request.getParameter("quantity"));
        // 2.1 通过商品id查询详情
        ProductService productService = new ProductServiceImpl();
        Product product = productService.findById(pid);
        // 2.2 获得购物车
        Cart cart = getCart(request.getSession());
        // 2.3 将商品添加到购物车
        cart.addCart(product, count);
        // 3.重定向到购物车页面
        response.sendRedirect(request.getContextPath() + "/jsp/cart.jsp");
        return null;
    }

    /**
     * 从session获取购物车
     *
     * @param session
     * @return
     */
    private Cart getCart(HttpSession session) {
        Cart cart = (Cart) session.getAttribute("cart");
        if (null == cart) {
            //如果获取不到,创建购物车对象,放在session中
            cart = new Cart();
            session.setAttribute("cart", cart);
        }
        return cart;
    }
    /**
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    public String clearCart(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取购物车
        Cart cart=getCart(req.getSession());
        // 2.调用购物车上的清空购物车方法
        cart.clearCart();
        // 3.重新定向到/jsp/cart.jsp
        resp.sendRedirect(req.getContextPath()+"/jsp/cart.jsp");
        return null;
    }
    /**
     * 从购物车中移除商品
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    public String removeCart(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取请求参数，商品id
        String pid = req.getParameter("id");
        // 2.1 获得购物车
        Cart cart = getCart(req.getSession());
        // 2.2 将商品从购物车中移除
        cart.removeCartItem(pid);
        // 3.重定向到购物车页面
        resp.sendRedirect(req.getContextPath()+"/jsp/cart.jsp");
        return null;
    }
}